<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示区域 -->

      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        center
        show-icon
      >
      </el-alert>

      <!-- 步骤条区域 -->

      <el-steps
        :space="200"
        finish-status="success"
        :active="activeIndex - 0"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="商品完成"></el-step>
      </el-steps>

      <!-- 标签区域 -->

      <el-form
        :model="addgoodsForm"
        :rules="addgoodsFormRules"
        ref="addgoodsFormref"
        label-width="180px"
        :label-position="'top'"
      >
        <el-tabs
          :before-leave="beforLeaveTab"
          v-model="activeIndex"
          :tab-position="'left'"
          @tab-click="tabClick"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addgoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                type="number"
                v-model="addgoodsForm.goods_price"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_wight">
              <el-input v-model="addgoodsForm.goods_wight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                type="number"
                v-model="addgoodsForm.goods_number"
              ></el-input>
            </el-form-item>
            <!-- 级联选择器 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addgoodsForm.goods_cat"
                :options="cateList"
                :props="cateListProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item
              :label="item.attr_name"
              v-for="item in mantTableList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(cb, j) in item.attr_vals"
                  :label="cb"
                  :key="j"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item
              v-for="item in onlyTableList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <!-- action上传到后台的地址 -->
            <el-upload
              class="upload-demo"
              :action="uploadURl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="objHeahers"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor
              ref="myQuillEditorRef"
              v-model="addgoodsForm.goods_introduce"
            >
            </quill-editor>
            <el-button type="primary" @click="add" class="addBtns"
              >添加</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisibleImg" width="50%">
      <img class="imgPreview" :src="PreviewUrl" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'VueShopAdd',

  data() {
    return {
      activeIndex: "0",
      //   表单对象
      addgoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_wight: 0,
        goods_number: 0,
        // 商品分类
        goods_cat: [],
        // 临时图片地址
        pics: {},
        // 富文本内容
        goods_introduce: '',
        // 接受静态属性和动态参数
        attrs: []


      },
      addgoodsFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],

        goods_wight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }],

      },
      //   商品分类列表
      cateList: [],
      cateListProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'

      },
      //   动态参数
      mantTableList: [],
      //   静态属性
      onlyTableList: [],
      uploadURl: 'http://127.0.0.1:8888/api/private/v1/upload',
      //   在upload请求的时候手动配置一个请求头带上token
      objHeahers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 保存图片的绝对路径
      PreviewUrl: '',
      // 图片预览的对话框
      dialogVisibleImg: false



    }
  },
  created() {
    this.getCateList()
  },

  mounted() {

  },
  computed: {
    cateId() {
      return this.addgoodsForm.goods_cat.length === 3 ? this.addgoodsForm.goods_cat[2] : null
    },
  },

  methods: {

    //   获取商品分类列表  
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })
      //   console.log(res)
      this.cateList = res.data


    },

    // 监听级联选择器的改变
    handleChange() {
      if (this.addgoodsForm.goods_cat.length !== 3) {
        this.addgoodsForm.goods_cat = []
      }


    },
    // 监听表离开的事件
    beforLeaveTab(oldbeforleave, newbeforleave) {

      if (newbeforleave === '0' && this.addgoodsForm.goods_cat.length !== 3) {

        this.$message({ showClose: true, message: "请先选择商品分类", type: 'error' })
        return false
      }


    },
    // tab切换
    async tabClick() {
      //   console.log(this.activeIndex);
      //   获取动态参数
      // const ree = this.activeIndex - 0
      // console.log(typeof ree);
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })

        res.data.forEach(item => {

          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ")
        })
        if (res.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })



        this.mantTableList = res.data
        // console.log(this.mantTableList);

      } else if (this.activeIndex === '2') {

        const { data: res1 } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })


        if (res1.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })



        this.onlyTableList = res1.data
        console.log(this.onlyTableList)



      }



    },
    // 处理图片预览效果
    handlePreview(flie) {

      this.PreviewUrl = flie.response.data.url
      this.dialogVisibleImg = true
    },

    // 移除图片
    handleRemove(file) {
      //1找到图片的临时路径、2在数组中找到临时路径的索引，3利用splice删除
      // console.log(file)
      const temporaryPic = file.response.data.tmp_path

      let index = this.addgoodsForm.pics.findIndex(i => {
        i === temporaryPic
      })

      this.addgoodsForm.pics.splice(index, 1)
      console.log(this.addgoodsForm);






    },
    // 图片上传成功的钩子
    uploadSuccess(response) {
      // console.log(response)
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addgoodsForm.pics.push(picInfo)
      // console.log(this.addgoodsForm)

    },
    // 添加商品
    add() {
      this.$refs['addgoodsFormref'].validate(async (valid) => {

        if (!valid) {
          this.$message.error('请输入正确的表单项')
          return false
        }
        // 发送网络请求 保存数据
        // 执行添加业务

        //  深拷贝addgoodsForm对象
        const form = _.cloneDeep(this.addgoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数项
        this.mantTableList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addgoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addgoodsForm.attrs.push(newInfo)
        })
        form.attrs = this.addgoodsForm.attrs

        const { data: res } = await this.$http.post('goods', form)
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

        }


        this.$message({ showClose: true, message: '添加商品成功', type: 'success' })

        this.$router.push('/goods')






      })

    }



  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-steps_title {
  font-size: 13px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.imgPreview {
  width: 100%;
}
.quill-editor /deep/.ql-editor {
  height: 300px !important;
}
.addBtns {
  margin-top: 15px;
}
</style>